﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Collections.Specialized;
using System.Threading;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
using NOS.Core;
using System.IO;
using NOS.Security;
using System.Web;

namespace NOS.Server
{
    public class NOSServer
    {

        #region . Variaveis .

        private string Port = "";

        private HttpListener httplis = null;

        #endregion

        #region . Funções Publicas .

        public void Start()
        {
            httplis = new HttpListener();
            Trace.WriteLine("\nhttpListener created...");

            try
            {
                Trace.Write("Getting the port number, ");
                Port = ":" + ConfigurationManager.AppSettings.GetValues("Port").GetValue(0);
                Trace.WriteLine(" post is: "+Port);
            } catch { }
                       
            httplis.Prefixes.Add("http://*"+Port + "/");
            Trace.Write("Add http://*" + Port + "/ for listen\n");

            httplis.Start();

            Trace.WriteLine("Service started\n");
            Trace.WriteLine("Listen in: "+Port);

            httplis.BeginGetContext(new AsyncCallback(WebRequestCallback), httplis);

            while (httplis.IsListening)
            {
                Thread.Sleep(50000);
            }           
        }

        #endregion

        #region . Funções Privadas .

        private void WebRequestCallback(IAsyncResult result)
        {
            HttpListenerContext context = httplis.EndGetContext(result);
            Trace.WriteLine("\nNew Call...");
            Trace.Write("Request: " + context.Request.UserHostAddress);
            Trace.WriteLine("  " + context.Request.UserAgent+"\n");

            httplis.BeginGetContext(new AsyncCallback(WebRequestCallback), httplis);
           
            Trace.WriteLine("New process");
                Process(context);
        }

        private void Process(HttpListenerContext Context)
        {
            NameValueCollection Parametros = new NameValueCollection();
            Trace.WriteLine("Calling NOS Core");
            
            NOSCore Nos = new NOSCore();

            if (Context.Request.HttpMethod == "POST")
            {
                Stream Input = Context.Request.InputStream;
                StreamReader Reader =  new StreamReader(Input, Context.Request.ContentEncoding);
                string _Parametros = Reader.ReadToEnd(); /*HttpUtility.ParseQueryString(*//*,Context.Request.ContentEncoding)*/ 
            }
            else
            {
                Parametros = Context.Request.QueryString;
            }
            string Nosresponse = "";

            Nosresponse = Nos.Process(Context.Request.Url.AbsolutePath, Parametros);

            WriteResponse(Context.Response,Nosresponse);
        }

        private void WriteResponse(HttpListenerResponse Response, string ResponsetoWrite)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(ResponsetoWrite);
            Response.ContentLength64 = buffer.Length;
            Stream output = Response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }

        #endregion
    }
}